# coding=utf-8
from tools import Tools

__author__ = 'Jiang Le'
from ui.select_art import Ui_ArtWindow
from PyQt4 import QtCore, QtGui
import os
import time
from hashlib import md5
import chardet
FAIL = -1


class ArticalCreater(Ui_ArtWindow):
    def __init__(self, src):
        self.src = src

    def setupUi(self, ArtWindow):
        Ui_ArtWindow.setupUi(self, ArtWindow)
        self.window = ArtWindow
        self.doCreate.clicked.connect(self.doCreate_btn_click)

    def doCreate_btn_click(self):
        self.name = str(self.name_text.text().toUtf8())
        self.title = str(self.title_text.text().toUtf8())
        self.descripition = str(self.descripition_text.text().toUtf8())
        self.tags = str(self.tag_text.text().toUtf8())
        if self.cemment_checkbox.isChecked():
            self.comments = "True"
        else:
            self.comments = "False"
        if not self.name:
            self.alert(u"请填写文件名")
            return
        self.create_file()

    def create_file(self):
        os.chdir(self.src)
        # 通过QT控件获取到的都是UTF编码的
        path = (self.name + ".md").decode("utf8")
        if os.path.exists(path):
            self.alert(u"创建文件失败,文件已存在")
            return FAIL
        else:
            with open(path, "w") as f:
                cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                cur_time_md5 = md5(cur_time)
                f.write("id : " + cur_time_md5.hexdigest() + "\n")
                f.write("date : " + cur_time + "\n")
                if self.title:
                    f.write("title : " + self.title + "\n")
                if self.descripition:
                    f.write("descripition : " + self.descripition + "\n")
                if self.tags:
                    f.write("tags : " + self.tags + "\n")
                f.write("comments : " + self.comments + "\n")
                f.write("\n---\n")
            if self.alert(u"文件创建成功") == QtGui.QMessageBox.Ok:
                self.window.close()

    @staticmethod
    def alert(message):
        return QtGui.QMessageBox.question(None, u"警告", message, QtGui.QMessageBox.Ok)
